﻿namespace NMortgage.UI.Converters
{
    using System;
    using System.Globalization;
    using System.Resources;
    using System.Windows;
    using System.Windows.Data;

    /// <summary>
    /// Converts the given enum value to its friendly display text using the <code>ResourceKeyAttribute</code> or by convention EnumTypeName_EnumValueName in the given <code>ResourceManager</code>
    /// </summary>
    public class EnumToResourceConverter : IValueConverter
    {
        #region Methods

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var resourceManager = parameter as ResourceManager;

            if (ReferenceEquals(value, null) || ReferenceEquals(resourceManager, null))
                return null;

            var type = value.GetType();
            if (type.IsEnum)
            {
                return GetByConvention(resourceManager, value, culture);
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue; // not supported
        }

        private static object GetByConvention(ResourceManager resourceManager, object value, CultureInfo culture)
        {
            var type = value.GetType();
            var key = type.Name + "_" + Enum.GetName(type, value);
            var resourceValue = resourceManager.GetObject(key, culture);
            return !ReferenceEquals(resourceValue, null) ? resourceValue : value.ToString();
        }

        #endregion Methods
    }
}